<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Promise</title>
</head>
<body>
	<script>
		function timeout(ms) {
			return new Promise((resolve, reject) => {
				setTimeout(resolve, ms, 'done');
			})
		}
		//timeout(100).then(value => {console.log(value);})
		//console.log(1)
/*
		let promise = new Promise((resolve, reject) => {
			console.log('Promise');
			resolve && resolve();
		})*/
		//promise.then(() => {console.log('resolved.')},() => console.log('Err'))
		//console.log("Hi!")

		function loadImageAsync(url) {

			return new Promise( (resolve, reject) => {
				const img = new Image();
				img.onload = () => {
					resolve(img)
				}

				img.onerror = () => {
					reject( new Error(`Could not load img at ${url}`) );
				}

				img.src = url ;
			})
			
		}

		const getJSON = function (url)　{

			return new Promise( (resolve, rejected) => {
				let handler = function () {
					if ( this.readyState !==4 )
						return ;
					if ( this.status === 200 ) {
						resolve(this.response)
					} else {
						rejected(new Error(this.statusText))
					}
				}
				let client = new XMLHttpRequest()
				client.open('GET', url)
				client.onreadystatechange = handler
				client.responseType = 'json'
				client.setRequestHeader('Accept', 'application/json')
				client.send(null)

			})

		}

/*		const p1 = new Promise(function (resolve, rejected) {
			setTimeout(() => rejected(new Error('fial')), 3000)
		})

		const p2 = new Promise(function (resolve, rejected) {
			setTimeout(() => resolve(p1), 1000)
		})

		p2
		  .then(result => console.log(result))
		  .catch(error => console.error(error))*/
/*		  setTimeout(() => console.log(1),10)
		  new Promise((resolve, reject) => {
		  	setTimeout(()=>{resolve(2)},10)
		  	console.log(3)
		  }).then(r => {
		  	console.log(r)
		  })*/

/*		  new Promise((resolve, reject) => {		  	
		  	console.log(2);
		  	return resolve(1);
		  	console.log(2);
		  })*/
		  new Promise((res, rej) => {
		  	return res(1)
		  }).then(v => console.log(v))

	</script>
</body>
</html>